package day_07;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class LruCache<K, V> {
    // 默认负载因子
    private static final float DEFAULT_LOAD_FACTORY = 0.75F;
    // 最大缓存数量
    private static final int MAX_CACHE_SIZE = 10;
    // LinkedHashMap
    private final MyLinkedHashMap map;

    // 默认size为16
    public LruCache() {
        map = new MyLinkedHashMap(16, DEFAULT_LOAD_FACTORY, true);
    }

    public LruCache(int initialCapacity) {
        map = new MyLinkedHashMap(initialCapacity, DEFAULT_LOAD_FACTORY, true);
    }

    public void put(K k,V v){
        map.put(k, v);
    }

    public V get(K k){
        return map.get(k);
    }

    public int size(){
        return map.size();
    }

    public void remove(K k){
        map.remove(k);
    }

    public Set<K> keySet(){
        return map.keySet();
    }



    private class MyLinkedHashMap extends LinkedHashMap<K, V> {
        public MyLinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) {
            super(initialCapacity, loadFactor, accessOrder);
        }

        @Override
        protected boolean removeEldestEntry(Map.Entry eldest) {
            return MAX_CACHE_SIZE < size();
        }
    }
}
